<?php
require_once('Loader/Index.php');

class Loader_Dispatcher{
	public $object;

	function handleEvent($ClassName=null/*PathClassName,method,params*/){
		global $config;
		// http://www.21w.pl/strona,class,metoda,vars.html
		if (!is_null($ClassName)) return Loader_Dispatcher::initClass($ClassName);
	}
	
	function __get($ClassName){
		if (!is_null($ClassName)) return Loader_Dispatcher::getClass($ClassName);		
	}
	
	
	private function initClass($parameters__=null){
		global $parameters, $config;
		
		$p__ = $parameters['testy']['speed'];
		
		if ( $p__ ) $timestart = microtime();
		$ret = null;
		
		$arr__ = explode(',',$parameters__);
		$pclass__ = str_replace('_','/',$arr__[0]);
		$nclass__ = explode('/',$pclass__);
		$class__ = "{$nclass__[count($nclass__)-1]}Controller";
		$method__ = isset($arr__[1])?$arr__[1].'Action':'indexAction';	
		$par__ = isset($arr__[2])?$arr__[2]:null;
		$path__ = explode(PATH_SEPARATOR,get_include_path());
		foreach ($path__ as $path) {
			if (is_file("$path/$pclass__.php")) include_once("{$pclass__}.php");
		}	
		if(isset($this->object[$class__]) && is_object($this->object[$class__])){
			if (method_exists($this->object[$class__] ,$method__)) $this->object[$class__]->$method__($par__);			
		}else if (class_exists("$class__")){			
			$this->object[$class__] = new $class__($par__);
			if (method_exists($this->object[$class__] ,$method__)) $this->object[$class__]->$method__($par__);
		}else{
			$ret = false;
		}
		if ( $p__ ){
			$timeend = microtime();
			$config->runtime .=tools::differencesBetweenTwoTimes($timestart,$timeend)." - {$class__}->{$method__}({$par__})\n";
		}
		return $ret;
	}
	
	private function getClass($parameters__=null){
		global $config, $parameters;
		$p__ = $parameters['testy']['speed'];
		if ( $p__ ) $timestart = microtime();
		
		
		$arr__ = explode(',',$parameters__);
		$pclass__ = str_replace('_','/',$arr__[0]);
		$nclass__ = explode('/',$pclass__);
		$class__ = "{$nclass__[count($nclass__)-1]}Controller";
		$path__ = explode(PATH_SEPARATOR,get_include_path());
		foreach ($path__ as $path) {
			if (is_file("$path/$pclass__.php")) include_once("{$pclass__}.php");
		}	
		if(isset($this->object[$class__]) && is_object($this->object[$class__])){
			if ( $p__ ){
				$timeend = microtime();
				$config->runtime .=tools::differencesBetweenTwoTimes($timestart,$timeend)." - {$class__}()\n";
			}
			return $this->object[$class__];			
		}else if (class_exists("$class__")){			
			$this->object[$class__] = new $class__();
			if ( $p__ ){
				$timeend = microtime();
				$config->runtime .=tools::differencesBetweenTwoTimes($timestart,$timeend)." - {$class__}()\n";
			}
			return $this->object[$class__];
		}else{
			return null;
		}
	}
	
	
	
}
